package com.gongpingjialoan.activity.car;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.adapter.CarSourceListAdapter;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.api.Piont;
import com.gongpingjialoan.bean.CarSource;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.manage.PointRecordManage;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.widget.LoadingDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by Administrator on 2015/12/16.
 */
public class SameCityRankActivity extends BaseActivity implements AbsListView.OnItemClickListener, NetDataJson.OnNetDataJsonListener {

    private ListView mListView;

    private ImageView nodataImageView;

    private CarSourceListAdapter mSelectCarSourceListAdapter;

    public ArrayList<CarSource> mCarSourceList;

    private NetDataJson netWork;

    private String cityName, brand, model, model_detail, car_id ,price_rank;

    private LoadingDialog loadingDialog;

    private int selectId;

    private int rank = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isSendData = true;
        isScrollPage = true;
        action = "detail_rank";
        super.onCreate(savedInstanceState);
        setContentView(R.layout.same_rank_layout);
        setTitle("同城排名");
        cityName = getIntent().getStringExtra("cityName");
        brand = getIntent().getStringExtra("brand");
        model = getIntent().getStringExtra("model");
        String StringRank =  getIntent().getStringExtra("price_rank");
        model_detail = getIntent().getStringExtra("model_detail");
        car_id = getIntent().getStringExtra("car_id");
        loadingDialog = new LoadingDialog(this);
        mListView = (ListView) findViewById(R.id.list_view);
        mListView.setDividerHeight(0);
        nodataImageView = (ImageView) findViewById(R.id.no_data);
        mCarSourceList = new ArrayList<>();
        mSelectCarSourceListAdapter = new CarSourceListAdapter(this);
        mSelectCarSourceListAdapter.setCarId(car_id);
        mListView.setAdapter(mSelectCarSourceListAdapter);
        mListView.setOnItemClickListener(this);
        if (GPJApplication.getInstance().getCarSource() != null) {
            selectId = GPJApplication.getInstance().getCarSource().mId;
        }
        if(!TextUtils.isEmpty(StringRank)){
            rank = Integer.parseInt(StringRank);
        }
        initData();
    }

    private void initData() {
        if (netWork == null)
            netWork = new NetDataJson(this);
        netWork.setUrl(API.carListSearch);
        netWork.addParam("city", cityName);
        netWork.addParam("sort", "price");
        netWork.addParam("page", 1);
        if (brand != null)
            netWork.addParam("brand", brand);
        if (model != null)
            netWork.addParam("model", model);
        if (model_detail != null)
            netWork.addParam("model_detail", model_detail);
        netWork.request("get");
        loadingDialog.show();

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        PointRecordManage.getInstance().addPoint(mySelf, Piont.SourceSameCityDetailClick);
        Intent intent = new Intent();
        intent.setClass(this, CarBuyDetailActivity.class);
        CarSource carSource = (CarSource) view.getTag(R.id.tag_second);
        intent.putExtra("typevalue", String.valueOf(carSource.mId));
        intent.putExtra("type", "tongcheng");
        intent.putExtra("from", "cityrange");
        startActivity(intent);
    }

    @Override
    public void onDataJsonError(String errorMessage) {
        Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
        loadingDialog.dismiss();
    }

    @Override
    public void onDataJsonUpdate(JSONObject json) {
        loadingDialog.dismiss();
        JSONArray jsonArray = null;
        try {
            jsonArray = json.getJSONArray("car_list");
            if (0 == jsonArray.length()) {
                nodataImageView.setVisibility(View.VISIBLE);
                Toast.makeText(this, "未找到相应数据", Toast.LENGTH_SHORT).show();
                return;
            }
            getDataFromJsonArray(jsonArray);
        } catch (JSONException e) {
            Toast.makeText(this, "未找到相应数据", Toast.LENGTH_SHORT).show();

            return;
        }

        updateListView();
    }

    private void updateListView() {
        if (mCarSourceList.size() != 0) {
            mSelectCarSourceListAdapter.setData(mCarSourceList);
        } else {
            nodataImageView.setVisibility(View.VISIBLE);
        }
    }


    private void getDataFromJsonArray(JSONArray jsonArray) throws JSONException {
        // Log.e("getDataFromJsonArray", "getDataFromJsonArray");
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject object = jsonArray.getJSONObject(i);
            if( i == (rank-1) ){
                mCarSourceList.add(GPJApplication.getInstance().getCarSource());
            }
            if(selectId == object.getInt("id")){
                continue;
            }
            CarSource carSrc = new CarSource();
            carSrc.mCity = cityName;
            carSrc.mTitle = object.getString("title");
            carSrc.mYear = object.getString("year");
            carSrc.mMile = object.getString("mile").equals("None") ? "" : object.getString("mile");
            carSrc.mPrice = Double.valueOf(object.getString("price"));
            carSrc.mId = object.getInt("id");
            carSrc.pub_timestamp = object.getString("pub_timestamp");
            carSrc.mThumbnail = object.getString("thumbnail");
            carSrc.mTime = object.getString("time");
            carSrc.hasmodel = object.getString("has_model_detail");
            // carSrc.mRecommend = object.getString("recommend");
            carSrc.mSourceType = object.getString("source_type");
            carSrc.mGpjIndex = object.getDouble("gpj_index");
            carSrc.mQsTags = object.getString("qs_tags");
            carSrc.mSource = object.getString("domain");
            carSrc.dealer_category = object.getString("dealer_category");
            carSrc.is_certify = object.getBoolean("is_certify");
            carSrc.pubTime = object.getString("pub_time");
            carSrc.brand_zh = object.getString("brand_slug_zh");
            carSrc.model_zh = object.getString("model_slug_zh");
            carSrc.model_detail_zh = object.getString("model_detail_slug_zh");
            carSrc.setBrand(object.getString("brand_slug"));
            carSrc.setModel(object.getString("model_slug"));
            carSrc.isactive = object.getBoolean("seller_active");
            carSrc.origin_price = object.getString("origin_price");
            carSrc.lowest_price = object.getString("lowest_price");
            carSrc.last_price = object.getString("last_price");
            carSrc.cs_clean = object.getBoolean("cs_clean");
            carSrc.mUrl = carSrc.mThumbnail;
            mCarSourceList.add(carSrc);
        }


    }
}
